package refect;


import refect.domain.Person;

import java.lang.reflect.Field;

public class RefectDemo02Field {
    public static void main(String[] args)
            throws NoSuchFieldException, IllegalAccessException {

        // 0. 获取Class对象
        Class psersonClass = Person.class;

        // 1. Field[] getFields() : 获取所有publi成员变量

        Field[] fields = psersonClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("----------------");

        // 2. Field getField(String name)

        Field a = psersonClass.getField("a");
        // 获取成员变量 a 的值
        Person person = new Person();
        Object value = a.get(person);
        System.out.println(value);  // null
        // 设置值
        a.set(person, "张三");
        System.out.println(a.get(person)); // 张三

        System.out.println("----------------");

        // 3. Field[] getDeclaredFields() : 获取所有已经声明的成员变量

        Field[] declaredFields = psersonClass.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }

        System.out.println("----------------");

        // 4. Field getDeclaredField(String name)
        Field name = psersonClass.getDeclaredField("name");
        // 暴力反射: 忽略访问权限修饰符的安全检查
        name.setAccessible(true);
        Object valu2 = name.get(person);
        System.out.println(valu2);



    }

}
